package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"myapp/web/green/models"
	"myapp/web/green/models/orm"
	"strconv"
)

//创建新分类
type WarehouseCreate struct {
	beego.Controller
}

func (this *WarehouseCreate) Post() {
	var w orm.Warehouse
	body := this.Ctx.Input.RequestBody
	json.Unmarshal(body, &w)
	w.Level = 0
	var ws models.Creater = &w
	o := models.NewOrmer()
	num, err := o.QueryTable("_goods").Filter("_warehouseid", w.Fid).Count()
	fmt.Println("num: ", num)
	if err == nil && num == 0 {
		num2, err := o.QueryTable("_warehouse").Filter("_name", w.Name).Filter("_fid", w.Fid).Count()
		fmt.Println("num2: ", num2)
		if err == nil && num2 == 0 {
			id, err := ws.Create(o)
			if err != nil {
				this.Data["json"] = &HttpMessage{Status: 1} //1表示数据库操作出错！
			} else {
				this.Data["json"] = &HttpMessage{Status: 0, Data: id}
			}
		} else {
			this.Data["json"] = &HttpMessage{Status: 3} //3表示该分类下名称重复，不可创建新分类!
		}
	} else {
		this.Data["json"] = &HttpMessage{Status: 2} //2表示该分类下有物品，不可创建新分类!
	}
	this.ServeJson()
	fmt.Println("warehouse create err: ", err)
}

//更新分类
type WarehouseUpdate struct {
	beego.Controller
}

func (this *WarehouseUpdate) Post() {
	var w orm.Warehouse
	body := this.Ctx.Input.RequestBody
	json.Unmarshal(body, &w)
	var ws models.Updater = &w
	o := models.NewOrmer()
	num, err := o.QueryTable("_warehouse").Filter("_name", w.Name).Filter("_fid", w.Fid).Count()
	fmt.Println("num: ", num)
	if err == nil && num == 0 {
		err := ws.Update(o)
		if err != nil {
			this.Data["json"] = &HttpMessage{Status: 1} //1表示数据库操作出错！
		} else {
			this.Data["json"] = &HttpMessage{Status: 0}
		}
	} else {
		this.Data["json"] = &HttpMessage{Status: 2} //2表示该分类下名称重复，不可创建新分类!
	}

	this.ServeJson()
	fmt.Println("warehouse update err: ", err)
}

//删除分类
type WarehouseDelete struct {
	beego.Controller
}

func (this *WarehouseDelete) Get() {
	id := this.Ctx.Input.Param(":id")
	id2int, _ := strconv.Atoi(id)
	var ws models.Deleter = &orm.Warehouse{Id: id2int}
	o := models.NewOrmer()
	err := ws.Delete(o)
	if err != nil {
		this.Data["json"] = &HttpMessage{Status: 1}
	} else {
		this.Data["json"] = &HttpMessage{Status: 0}
	}
	this.ServeJson()
	fmt.Println("warehouse delete err: ", err)
}

//取得分类列表
type WarehouseList struct {
	beego.Controller
}

func (this *WarehouseList) Post() {
	var ws models.Lister = &orm.Warehouse{}
	o := models.NewOrmer()
	list, err := ws.List(o)
	if err != nil {
		this.Data["json"] = &HttpMessage{Status: 1}
	} else {
		this.Data["json"] = &list
	}
	this.ServeJson()
	fmt.Println("warehouse list err: ", err)
}
